<template>
<div class="app-container">
   <loading v-show="loading"></loading>
  <el-card class="box-card searchFormStyle" style="margin-bottom:1%;">
    <div slot="header" class="clearfix">
      <span>角色操作</span>
    </div>
    <div class="text item">
      <el-form ref="SearchRole" :model="SearchRole" label-width="130px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="角色名称"  prop="name">
              <el-input v-model="SearchRole.roleName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="角色状态"  prop="status">
              <el-select v-model="SearchRole.enableState" placeholder="请选择" style="width:100%;">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item>
              <el-button type="primary" icon="el-icon-plus" @click="addRole" v-if="permissionHandle('role:openDialog')">新 增</el-button>
              <el-button type="primary" icon="el-icon-search" @click="searchRole" v-if="permissionHandle('role:getList')">查 询</el-button>
              <el-button type="primary" icon="el-icon-refresh" @click="resetSearch" v-if="permissionHandle('role:getList')">重 置</el-button>
              <el-button type="info" icon="el-icon-delete" @click="BatchDeleting" v-if="permissionHandle('role:handleDelete')">删 除</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </el-card>
  <el-card class="box-card" style="margin-bottom:1%;">
    <div slot="header" class="clearfix">
      <span>角色列表</span>
    </div>
    <el-table
      :data="tableData"
      border
      style="width: 100%;margin-bottom:1%;"
      @selection-change="handleSelectionChange"
      >
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column
        label="角色名称"
        width="180">
        <template slot-scope="scope">
            {{ scope.row.roleName }}
        </template>
      </el-table-column>
      <el-table-column label="角色状态">
        <template slot-scope="scope">
          {{ scope.row.enableState==='001'?'可用':'禁用' }}
        </template>
      </el-table-column>
      <el-table-column
        width="180"
        label="创建日期">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span style="margin-left: 10px">{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="300px">
        <template slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-setting"
            @click="handleauth(scope.$index, scope.row)"
             v-if="permissionHandle('role:handleAuth')"
            size="mini">
            授权
          </el-button>
          <el-button
            size="mini"
            icon="el-icon-edit-outline"
            v-if="permissionHandle('role:handleEdit')"
            @click="handleEdit(scope.$index, scope.row)">修改</el-button>
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            v-if="permissionHandle('role:handleDelete')"
            @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pagerCount" :page-sizes="[10,20,30, 50]" :page-size="10" layout="sizes, prev, pager, next" :total="200">
    </el-pagination> -->
    <el-pagination
      background
      layout="prev, pager, next"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-count="totalPage">
    </el-pagination>
  </el-card>
  <!--新增角色-->
  <el-dialog :title="title" :visible.sync="dialogFormVisible">
    <el-form :model="addForm" :rules="rules" ref="addForm" label-width="100px">
      <el-row>
        <el-col :span="12">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="addForm.roleName" auto-complete="off"></el-input>
            </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="角色状态" prop="enableState">
            <el-select v-model="addForm.enableState" placeholder="请选择角色状态">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input type="textarea" v-model="addForm.roleDesc" auto-complete="off"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="roleSubmitSuccess('addForm')">确 定</el-button>
    </div>
  </el-dialog>
  <!-- -------------------------------------------------授权角色 -->
  <el-dialog title="授权角色" :visible.sync="dialogAuthVisible" width="40%" class="authBox">
    <div>
      <el-tree
        :data="dataList"
        ref="tree"
        show-checkbox
        node-key="id"
        :default-expand-all="false"
        :default-checked-keys="checkdefault"
        :props="defaultProps">
      </el-tree>
    </div>
    <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="authSubmitSuccess">确 定</el-button>
      </div>
  </el-dialog>
  <!-- -------------------------------------------------授权角色 -->
</div>
</template>
<script>
import Loading from '@/components/loading/loading'
import { transform } from '@/utils/trans'
// import treeTable from '@/components/TreeTable'
import { isvalidRequire, isvalidSpecial } from '@/utils/validate'
// 非空
var validateRequire = (rule, value, callback) => {
  if (!isvalidRequire(value)) {
    callback(new Error('请输入必填项'))
  } else {
    callback()
  }
}
// 特殊字符
var validSpecial = (rule, value, callback) => {
  if (!isvalidSpecial(value)) {
    callback(new Error('数据不能包含特殊字符'))
  } else {
    callback()
  }
}
import { roleList, addAllRole, delRole, authRole, queryAllAuth } from '@/api/resource/role'
export default {
  components: {
    Loading
  },
  data() {
    this.permissionHandle = this.$permissionHandle
    return {
      rules: {
        roleName: [
          { required: true, message: '不能为空' },
          { message: '数据不能包含特殊字符', validator: validateRequire },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        enableState: [
          { required: true, message: '不能为空' },
          { message: '数据不能包含特殊字符', validator: validateRequire }
        ],
        roleDesc: [
          { message: '数据不能包含特殊字符', validator: validSpecial },
          { min: 1, max: 10, message: '长度在 1 到 200 个字符', trigger: 'blur' }
        ]
      },
      SearchRole: {
        roleName: '',
        enableState: ''
      },
      loading: false,
      authloading: false,
      options: [{
        value: '001',
        label: '可用'
      }, {
        value: '000',
        label: '禁用'
      }],
      tableData: [],
      // 新增角色数据
      addForm: {
      },
      title: '',
      dialogFormVisible: false, // 新增弹出框状态
      // 列表所选数据集合
      multipleSelection: [],
      totalPage: 1,
      dialogAuthVisible: false, // 授权弹出框状态
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      roleId: '',
      allAuth: [],
      flag: 1,
      typeRole: [],
      dataList: [],
      roleKey: '',
      currentPage: 1,
      checkdefault: []// 默认授权
    }
  },
  created() {
    this._roleList()
  },
  methods: {
    // 获取角色数据
    _roleList() {
      this.handleCurrentChange(1)
    },
    // 点击新增角色
    addRole() {
      this.title = '新增角色'
      this.roleKey = []
      this.dialogFormVisible = true
      this.addForm = {}
    },
    // 新增成功
    roleSubmitSuccess(addForm) {
      // debugger
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.loading = true
          this.dialogFormVisible = false
          addAllRole({
            roleName: this.addForm.roleName,
            roleDesc: this.addForm.roleDesc,
            enableState: this.addForm.enableState,
            roleKey: this.roleKey

          }).then(res => {
            if (res.code === 200) {
              this.openwarning('提交成功', 'success')
              this.handleCurrentChange(1)
              this.$refs.addForm.resetFields()
            }
          }).catch(error => {
            console.log(error)
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 角色查询
    searchRole() {
      this.handleCurrentChange(1)
    },
    // 编辑角色
    handleEdit(index, row) {
      this.title = '修改角色'
      this.dialogFormVisible = true
      this.addForm = {
        roleName: row.roleName,
        enableState: row.enableState === '001' ? '可用' : '禁用',
        roleDesc: row.roleDesc
      }
      this.roleKey = row.roleKey
    },
    // 授权点击事件
    handleauth(index, row) {
      this.roleId = row.roleKey
      this.dialogAuthVisible = true
      this.loading = true
      queryAllAuth({
        roleId: row.roleKey
      }).then(res => {
        if (res.code === 200) {
          this.loading = false
          this.checkdefault = []
          // console.log(res.data.resources)
          res.data.resourceIds.forEach(val => {
            res.data.resources.forEach(el => {
              // debugger
              if (el.id === val.resourceId) {
                val.type = el.type
              }
            })
          })
          res.data.resourceIds.forEach(val => {
            if (val.type !== 1) {
              this.checkdefault.push(val.resourceId)
            }
          })
          const typeRole = res.data.resources.filter(item => item.type !== 3)
          // console.log(typeRole)
          this.data3 = res.data.resources.filter(item => item.type === 3)
          this.dataList = transform(typeRole, 'id', 'pId', 'children')
        }
      }).catch(error => {
        this.loading = false
        console.log(error)
      })
    },
    // 角色授权成功
    authSubmitSuccess() {
      const auth = []
      this.$refs.tree.getHalfCheckedNodes().forEach(val => {
        auth.push(val.id)
      })

      this.$refs.tree.getCheckedNodes().forEach(val => {
        auth.push(val.id)
      })
      auth.forEach(idx => {
        this.data3.forEach(el => {
          // debugger
          if (el.pId === idx) {
            auth.push(el.id)
          }
        })
      })
      this.dialogAuthVisible = false
      console.log(auth)
      const data = {
        roleKey: this.roleId,
        resourceIds: auth
      }
      authRole(data).then(res => {
        this.openwarning('授权成功', 'success')
      })
    },
    // 批量删除
    BatchDeleting() {
      if (this.multipleSelection.length !== 0) {
        const result = []
        this.multipleSelection.forEach(val => {
          result.push(val.roleKey)
        })
        delRole({
          id: result.join(',')
        }).then(res => {
          if (res.code === 200) {
            this.handleCurrentChange(1)
            this.openwarning('删除成功', 'success')
          }
        }).catch(error => {
          console.log(error)
        })
      } else {
        this.openwarning('请选择要删除数据', 'warning')
      }
    },
    handleDelete(index, row) { // 行内删除
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this._delRole(row)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    _delRole(row) {
      delRole({
        id: row.roleKey
      }).then(res => {
        if (res.code === 200) {
          this.handleCurrentChange(1)
        }
      }).catch(error => {
        console.log(error)
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleSizeChange(val) {
      console.log(val)
    },
    handleCurrentChange(val) {
      console.log(val)
      this.loading = true
      roleList({
        pageSize: 10,
        pageNum: val,
        roleName: this.SearchRole.roleName,
        enableState: this.SearchRole.enableState
      }).then(res => {
        if (res.code === 200) {
          this.loading = false
          this.currentPage = val
          this.tableData = res.data.items
          this.totalPage = res.data.pageTotalCount
        }
      }).catch(error => {
        this.loading = false
        console.log(error)
      })
    },
    openwarning(mes, type) {
      this.$message({
        showClose: true,
        message: mes,
        duration: 2000,
        type: type
      })
    },
    resetSearch() {
      this.SearchRole = {
        roleName: '',
        enableState: ''
      }
      this._roleList()
    }
  }
}
</script>
<style scoped>
.authBox >>> .el-dialog__body{
  max-height: 280px;
  overflow-y: scroll;
}
.dialog-footer{
  text-align: right;
  margin-top: 10px;
  /* position: absolute;
  margin-top: 0;
  right: 0; */
}
/* .el-tree-node .el-tree-node__children {
    display: flex!important;
    flex-wrap: wrap!important;
} */

</style>
